import { DynamicModule, Global, Module } from "@nestjs/common";
import { LogService } from "./log.service";
import { LoggerModule, Params } from "nestjs-pino";

import { EnumMicroService } from "../../../types/types";
import { configuration } from "../../../config/config";
import  { join } from "path";

const isDev = process.env.NODE_ENV === 'development';

@Global()
@Module({})
export class LogModule {
  static register(systemType: EnumMicroService): DynamicModule {

    const pinoConfig = {
      pinoHttp: {
        timestamp: () => `,"time":"${new Date().toLocaleString()}"`,
        transport: isDev
          ? {
            target: 'pino-pretty',
            options: {
              colorize: true,
              encoding: 'utf8', //  添加此行
            },
          }
          : {
            target: 'pino-roll',
            options: {
              file: join(
                configuration.logPathPrefix,
                systemType.toString(),
                `${systemType.toString()}.log`
              ),
              frequency: 'daily',
              mkdir: true,
              encoding: 'utf8', //  添加此行
            },
          },
        // 添加 customProps
        customProps: () => ({
          context: systemType, //  Use the actual enum value
        }),
        serializers: {
          req: (req) => {  // Use Request type from express
            return {
              method: req.method,
              url: req.url,
              params: req.params,
              query: req.query,
              body: req.body,
            };
          },
          res: (res) => {
            return {
              statusCode: res.statusCode,
              body: res.body,
            };
          },
          pid: () => undefined, //  或者 () => null,
          hostname: () => undefined, // 或者 () => null,
        },

        redact: ['req.headers.authorization', 'res.headers.cookie'],
      },
      mixin: () => { return {hostname: undefined}},
      pino: {
        level: isDev ? 'debug' : 'info',
        encoding: 'utf8', //  不添加会出现打印的日志是乱码的问题
      }
    };
    return {
      module: LogModule,
      imports: [LoggerModule.forRoot(pinoConfig)],
      providers: [LogService],
      exports: [LogService],
    };
  }
}
